﻿using UnityEngine;

namespace winS.Unity.Rendering
{
    /// <summary>
    /// 固定宽高比渲染器
    /// </summary>
    public class FixedAspectRenderer
    {
        /// <summary>
        /// 是否启用
        /// </summary>
        public bool enabled { get; private set; }

        /// <summary>
        /// 宽度比值
        /// </summary>
        public float widthRatio { get; private set; } = 1f;
        /// <summary>
        /// 高度比值
        /// </summary>
        public float heightRatio { get; private set; } = 1f;

        private float aspect;

        private IFixedAspectRenderExecutor fixedAspectRenderExecutor;

        public void Enable(float aspect, IFixedAspectRenderExecutor fixedAspectRenderExecutor)
        {
            if (aspect <= 0f) throw new System.Exception($"{nameof(FixedAspectRenderer)}.{nameof(Enable)}: 参数 {nameof(aspect)} 必须大于 0");
            if (enabled) return;
            enabled = true;
            this.aspect = aspect;
            this.fixedAspectRenderExecutor = fixedAspectRenderExecutor;
            Runtime.render.screen.onResolutionChanged += OnResolutionChanged;
            OnResolutionChanged(Runtime.render.screen.resolution);
        }
        /// <summary>
        /// 禁用固定宽高比渲染
        /// </summary>
        public void Disable()
        {
            if (!enabled) return;
            enabled = false;
            widthRatio = heightRatio = 1f;
            Runtime.render.screen.onResolutionChanged -= OnResolutionChanged;
        }

        public void Update()
        {
            OnResolutionChanged(Runtime.render.screen.resolution);
        }

        private void OnResolutionChanged(Vector2Int newResolution)
        {
            float aspectRate = (float)newResolution.x / newResolution.y / aspect;

            Rect rect;
            if (aspectRate > 1f)
            {
                heightRatio = 1f;
                widthRatio = 1f / aspectRate;
                rect = new Rect((1f - widthRatio) * 0.5f, 0f, widthRatio, heightRatio);
            }
            else
            {
                heightRatio = aspectRate;
                widthRatio = 1f;
                rect = new Rect(0f, (1f - heightRatio) * 0.5f, widthRatio, heightRatio);
            }

            fixedAspectRenderExecutor.Execute(rect);
        }
    }
}